package security

import (
	"encoding/json"
	"errors"

	"gitee.com/hp-huiw/my-go-core/util"
)

type IDField struct {
	value any
}

func NewIDField(value any) IDField {
	switch val := value.(type) {
	case int:
		return IDField{value: val}
	case int64:
		return IDField{value: val}
	case string:
		return IDField{value: val}
	default:
		return IDField{value: "unsupported type"}
	}
}

func (id *IDField) AsString() string {
	switch v := id.value.(type) {
	case int:
		return util.IntToString(v)
	case int64:
		return util.Int64ToString(v)
	case string:
		return v
	default:
		return ""
	}
}

func (id *IDField) AsInt64() (int64, error) {
	switch v := id.value.(type) {
	case int:
		return int64(v), nil
	case int64:
		return v, nil
	case string:
		int64Value, err := util.StringToInt64(v)

		if err != nil {
			return 0, err
		} else {
			return int64Value, nil
		}
	default:
		return 0, nil
	}
}

func (id *IDField) MarshalJSON() ([]byte, error) {
	switch v := id.value.(type) {
	case int, int64, string:
		return json.Marshal(v)
	default:
		return nil, errors.New("unsupported type for JSON")
	}
}

func (id *IDField) UnmarshalJSON(data []byte) error {
	var temp any

	if err := json.Unmarshal(data, &temp); err != nil {
		return err
	}

	switch v := temp.(type) {
	case int:
		id.value = int(v)
	case int64:
		id.value = int64(v)
	case string:
		id.value = string(v)
	default:
		return errors.New("unsupported type for JSON")
	}

	return nil
}
